package cn.zhaoyuening.hnistalumnirecord.web.controller.admin;

import cn.zhaoyuening.hnistalumnirecord.config.MyConstant;
import cn.zhaoyuening.hnistalumnirecord.domain.News;
import cn.zhaoyuening.hnistalumnirecord.domain.NewsModule;
import cn.zhaoyuening.hnistalumnirecord.service.NewsService;
import cn.zhaoyuening.hnistalumnirecord.tmp.QueryNewsExclusionStrategy;
import cn.zhaoyuening.hnistalumnirecord.utils.ImgUploadUtils;
import cn.zhaoyuening.hnistalumnirecord.utils.JsonDataGridData;
import cn.zhaoyuening.hnistalumnirecord.utils.page.ResponceResult;
import cn.zhaoyuening.hnistalumnirecord.web.controller.BaseController;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.tracing.dtrace.ModuleAttributes;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.IndexWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by zhao on 17-1-24.
 */
@Controller
@RequestMapping("admin/news/")
public class AdminNewsController extends BaseController{


    //分页查询news 并以json方式发回
//    @RequestMapping(value = "getNewsByPage.do" ,produces = "application/json; charset=utf-8")
//    @ResponseBody
    public String getNewsByPage(@RequestParam Integer startIndex, @RequestParam Integer pageSize,HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<News> newsList = getNewsService().findAll(null, null, startIndex, pageSize);
        Gson gson = new GsonBuilder().setExclusionStrategies(new QueryNewsExclusionStrategy()).create();
        JsonDataGridData jsonDataGridData = new JsonDataGridData();
        jsonDataGridData.setRows(newsList);
        jsonDataGridData.setTotal(getNewsAmount());
        String jsonData = gson.toJson(jsonDataGridData);
        return jsonData;
    }

    //进入news管理 ui
    @RequestMapping("newsManagerUi.do")
    public String newsManagerUi() {
        return "admin/newsManager";
    }


    //分页查询news 并以json方式发回
    @RequestMapping(value = "getNewsByPage.do" ,produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getNewsByPage2(@RequestParam Integer startIndex, @RequestParam Integer pageSize,@RequestParam Integer selectModule,@RequestParam String selectTitle,HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");

        JsonDataGridData jdgd = this.getNewsService().findByAdvancedQuery(selectModule, selectTitle, startIndex, pageSize);



        Gson gson = new GsonBuilder().setExclusionStrategies(new QueryNewsExclusionStrategy()).create();
        JsonDataGridData jsonDataGridData = new JsonDataGridData();
        jsonDataGridData.setRows(jdgd.getRows());
        jsonDataGridData.setTotal(jdgd.getTotal());
        String jsonData = gson.toJson(jsonDataGridData);
        return jsonData;
    }

    @RequestMapping("createNewsUi.do")
    public String createNewsUi() {
        return "admin/createNews";
    }

    @RequestMapping(value = "createNews.do",method = RequestMethod.POST)
    @ResponseBody
    public ResponceResult createNews(@ModelAttribute News news) throws IOException {
        getNewsService().save(news);
        return ResponceResult.successResult(null);
    }

    public long getNewsAmount() {
        Long totalRecord = getNewsService().getTotalRecord();
        return totalRecord;
    }

    //编辑news ui
    @RequestMapping("editNewsUi.do")
    public String editNewsUi(@RequestParam Integer id, Model model) {
        //获取news
        News news = getNewsService().findById(id);
        //将news的缩略图路径替换'\'为'/'
        String str = news.getThumbnailPath();
        if (str!=null){
            news.setThumbnailPath(StringUtils.replaceChars(str,"\\","/"));
        }
        model.addAttribute("news", news);
        return "admin/editNews";
    }

    //编辑news
    @RequestMapping("editNews.do")
    public String editNews(@RequestParam(value = "file",required = false) MultipartFile file,@ModelAttribute News news, Model model,HttpSession session) throws IOException {

        if ((!(file ==null))&&(!file.isEmpty())){
            //若上传了新的缩略图 替换
            String rootPath = session.getServletContext().getRealPath("/");
            String filePath = ImgUploadUtils.uploadImage(file,rootPath, MyConstant.newsThumbnailSavePath,UUID.randomUUID().toString());
            /*
            String filePath = "resource" + File.separatorChar + "uploadImg" + File.separatorChar+UUID.randomUUID().toString();
            File savePath = new File(rootPath+filePath);
            FileUtils.copyInputStreamToFile(file.getInputStream(),savePath);*/
            news.setThumbnailPath(File.separatorChar+filePath);
        }
        //将缩略图路径转换回来
        String str = news.getThumbnailPath();
        if (str != null) {
            news.setThumbnailPath(StringUtils.replaceChars(str,"\\","/"));
        }

        getNewsService().addOrEdit(news);
        model.addAttribute("result","修改文章成功！");
        return "admin/showResult";
    }
    //remove news
    @ResponseBody
    @RequestMapping("removeNews.do")
    public String removeNews(@RequestParam Integer id, Model model) {
        News news = new News();
        news.setId(id);
        getNewsService().delete(news);
        return "删除成功！";
    }


    //更新置顶基数 数越大 置顶级别越高
    @ResponseBody
    @RequestMapping(value = "updateOrderCount.do",produces = "text/plain;charset=utf-8")
    public String updateOrderCount(@RequestParam("id")Integer id,@RequestParam("orderCount")Integer orderCount){
        getNewsService().updateOrderCountById(id,orderCount);
        return "更改文章置顶级别为 "+orderCount+" 成功!";
    }


}
